import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage.js'
Vue.use(VueRouter)

const routes = [
  {
    path: '/detail/:id',
    name: 'detail',
    component: () => import('@/views/Detail.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/Login.vue')
  },
  {
    path: '/register',
    name: 'register',
    component: () => import('@/views/Register.vue')
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/views/Layout.vue'),
    redirect: '/layout/article',
    children: [
      {
        path: 'article',
        name: 'article',
        component: () => import('@/views/Article.vue')
      },
      {
        path: 'collect',
        name: 'collect',
        component: () => import('@/views/Collect.vue')
      },
      {
        path: 'my',
        name: 'my',
        component: () => import('@/views/My.vue')
      },
      {
        path: 'like',
        name: 'like',
        component: () => import('@/views/Like.vue')
      }
    ]
  }
]


const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, resolve, reject) {
  if (resolve || reject) return originalPush.call(this, location, resolve, reject)
  return originalPush.call(this, location).catch((e) => { })
}

const router = new VueRouter({
  routes
})
//设置白名单
//将对应的路径设置为白名单
const whiteList = ['/login', '/register']


// 路由导航守卫(钩子函数)
//全局前置路由导航守卫(拦截)
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 从哪个路径跳转而来
  // next 放行的方法
  const token = getToken()
  if (token) return next()
  //对部分页面不需要跳转的进行判断,否则会造成栈溢出
  if (whiteList.includes(to.path)) return next()
  next('/login')
  console.log(1)
})

// //全局后置路由导航守卫(判断)
// router.afterEach((to, from) => {

// })

export default router
